logo头像
Snippet 博客主题

Flutter 控件 Container

本文于325天之前发表,文中内容可能已经过时。

Flutter 控件 Container

Container的组成如下:

  • 最里层的是child元素;
  • child元素首先会被padding包着;
  • 然后添加额外的constraints限制;
  • 最后添加margin。

Container的绘制的过程如下:

  • 首先会绘制transform效果;
  • 接着绘制decoration;
  • 然后绘制child;
  • 最后绘制foregroundDecoration。

Container自身尺寸的调节分两种情况:

  • Container在没有子节点(children)的时候,会试图去变得足够大。除非constraints是unbounded限制,在这种情况下,Container会试图去变得足够小。
  • 带子节点的Container,会根据子节点尺寸调节自身尺寸,但是Container构造器中如果包含了width、height以及constraints,则会按照构造器中的参数来进行尺寸的调节。

Container 容器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
Container({
Key key,
this.alignment,
this.padding,
Color color,
Decoration decoration,
this.foregroundDecoration,
double width,
double height,
BoxConstraints constraints,
this.margin,
this.transform,
this.child,
})
Properties 含义
Key Container唯一标识符,用于查找更新。
alignment 控制child的对齐方式,如果container或者container父节点尺寸大于child的尺寸,这个属性设置会起作用,有很多种对齐方式。
padding decoration内部的空白区域,如果有child的话,child位于padding内部。padding与margin的不同之处在于,padding是包含在content内,而margin则是外部边界,设置点击事件的话,padding区域会响应,而margin区域不会响应。
color 用来设置container背景色,如果foregroundDecoration设置的话,可能会遮盖color效果。
decoration 绘制在child后面的装饰,设置了decoration的话,就不能设置color属性,否则会报错,此时应该在decoration中进行颜色的设置。
foregroundDecoration 绘制在child前面的装饰。
width container的宽度,设置为double.infinity可以强制在宽度上撑满,不设置,则根据child和父节点两者一起布局。
height container的高度,设置为double.infinity可以强制在高度上撑满。
constraints 添加到child上额外的约束条件。
margin 围绕在decoration和child之外的空白区域,不属于内容区域。
transform 设置container的变换矩阵,类型为Matrix4。
child container中的内容widget。

demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import 'package:flutter/material.dart';
class ContainerDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Center(
child: new Container(
width: 128.0,
height: 128.0,
decoration: new BoxDecoration(
color: Colors.lightBlueAccent[100],
),
),
);
}
}
void main() {
runApp(
new MaterialApp(
title: 'Flutter教程',
home: new ContainerDemo(),
),
);
}

demo1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import 'package:flutter/material.dart';
class ContainerDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new Center(
child: new Container(
width: 300.0,
height: 400.0,
decoration: new BoxDecoration(
color: const Color(0xfffce5cd),
border: new Border.all(
color: const Color(0xff6d9eeb),
width: 3.0,
),
),
child: new Text('容器演示'),
),
);
}
}
void main() {
runApp(
new MaterialApp(
title: 'Flutter教程',
home: new ContainerDemo(),
),
);
}
支付宝打赏 微信打赏

打赏